package hust.rpc.utils;

import java.util.HashMap;
import java.util.Map;

public class SingletonUtils {

    private static final Map<Class<?>, Object> objectMap = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> clazz) {
        Object instance = objectMap.get(clazz);
        if (instance == null) {
            synchronized (objectMap) {
                instance = objectMap.get(clazz);
                if (instance == null) {
                    try {
                        instance = clazz.newInstance();
                        objectMap.put(clazz, instance);
                    } catch (IllegalAccessException | InstantiationException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        }
        return (T) instance;
    }

    public static <T> void registerInstance(Class<T> clazz, Class<? extends T> o) {
        try {
            objectMap.put(clazz, o.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
